package com.springboot.stelleroid.timer;

import lombok.SneakyThrows;
import org.springframework.scheduling.support.CronSequenceGenerator;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author lianglei
 * <BR>此类用于测试时间轮调度算法<BR/>
 */
public class TimeWheelCase {
    private static CountDownLatch task1CountDownLatch = new CountDownLatch(1);
    private static CountDownLatch task2CountDownLatch = new CountDownLatch(1);
    private static CountDownLatch task3CountDownLatch = new CountDownLatch(1);
    private static CountDownLatch task4CountDownLatch = new CountDownLatch(1);

    private static class DelayTestTask1 implements TimerTask {
        @SneakyThrows
        @Override
        public void run(Timeout timeout) {
            System.out.println("TestTask1");
            task1CountDownLatch.countDown();
        }
    }

    private static class TestTask2 implements TimerTask {
        @Override
        public void run(Timeout timeout) {
            System.out.println("TestTask2");
            task2CountDownLatch.countDown();
        }
    }


    private static class ImmediatelyTask implements TimerTask {
        @Override
        public void run(Timeout timeout) {
            System.out.println("ImmediatelyTask");
            task3CountDownLatch.countDown();
        }
    }


    private static class  CronTask implements TimerTask {
        @Override
        public void run(Timeout timeout) {
            System.out.println("CronTask");
            task3CountDownLatch.countDown();
        }
    }




    public static void main(String[] args) throws InterruptedException {
        Timer timer = new HashedWheelTimer(new NamedThreadFactory("future-timeout", true));
        // 1 todo 延迟任务执行
        timer.newTimeout(new DelayTestTask1(), 5, TimeUnit.SECONDS);
        task1CountDownLatch.await();
        timer.newTimeout(new TestTask2(), 5,TimeUnit.SECONDS);
        task2CountDownLatch.await();

        // 2 todo 立即执行
       Timeout immediatelyTaskTimer = timer.newTimeout(new ImmediatelyTask(), 0, TimeUnit.SECONDS);
        task3CountDownLatch.await();



        //3 todo 固定时间点执行，或者周期执行，下个月第二个星期二上午八点
        String cron="0 0/10 * * * ? ";
        CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cron);
        Date next = cronSequenceGenerator.next(new Date());
        Timeout timeout = timer.newTimeout(new CronTask(),next.getTime(), TimeUnit.SECONDS);
        task4CountDownLatch.await();
    }
}
